<template>
  <div class="page-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="110px">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="base">
          <br>
          <br>
          <el-col :span="16" :offset="2">
            <el-form-item ref="titleItem" label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="作者" prop="author">
              <el-input v-model="formData.author" placeholder="请输入文章作者" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="cateid">
              <el-select v-model="formData.cateid" placeholder="请选择">
                <el-option
                  v-for="item in $store.getters.allCate"
                  :key="item.id"
                  :label="item.catename"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="阅读次数" prop="click">
              <el-input-number v-model="formData.click" :min="1" :max="999" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" prop="create_date">
              <el-date-picker
                v-model="formData.create_date"
                type="datetime"
                placeholder="选择创建时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="是否推荐" prop="ishot">
              <el-switch
                v-model="formData.ishot"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否置顶" prop="istop">
              <el-switch
                v-model="formData.istop"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="2">
            <el-form-item label="收藏数量" prop="lovenum">
              <el-input v-model="formData.lovenum" placeholder="请输入收藏数量" type="text" onkeyup="this.value=this.value.replace(/\D/g,'')" />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="2">
            <el-form-item label="文章缩略图" prop="pic">
              <!-- :http-request="handleUpload"自定义上传 -->
              <el-upload
                class="upload-demo"
                action="http://124.223.14.236:8060/admin/common/upload?type=images"
                :headers="{ 'X-Token': this.$store.getters.token}"
                list-type="picture"
                :on-success="handleSuccess"
                :file-list="fileList"
                :limit="1"
                :before-upload="beforeUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="2">
            <el-form-item label="文章标签" prop="tags">
              <el-checkbox-group v-model="formData.tags">
                <el-checkbox v-for="item in tagList" :key="item.id" :label="item.tagname" name="type" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-tab-pane>
        <el-tab-pane label="SEO信息" name="seo">
          <br>
          <br>
          <el-col :span="16" :offset="2">
            <el-form-item label="SEO关键字" prop="keywords">
              <el-input v-model="formData.keywords" type="textarea" autocomplete="off" rows="3" placeholder="请输入seo关键字" />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="2">
            <el-form-item label="SEO的描述" prop="description">
              <el-input v-model="formData.description" type="textarea" autocomplete="off" rows="3" placeholder="请输入seo的描述" />
            </el-form-item>
          </el-col>
        </el-tab-pane>
        <el-tab-pane label="文章内容" name="content">
          <br>
          <br>
          <br>
          <el-col :span="19" :offset="1">
            <el-form-item label="文章内容" prop="content">
              <!-- <div ref="editorRef" /> -->
              <Editor :content.sync="formData.content" />
            </el-form-item>
          </el-col>
        </el-tab-pane>
      </el-tabs>
      <el-row type="flex" justify="center">
        <el-button type="success" icon="el-icon-plus" @click="submit(1)">立即发布</el-button>
        <el-button type="primary" icon="el-icon-folder-checked" @click="submit(2)">保存草稿</el-button>
        <el-button type="warning" icon="el-icon-back" @click="$router.push('/content_article')">返回列表</el-button>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { addArticle, editArticle, getAllTag, getArticleDetail } from '@/api/content/article'
import Editor from '@/components/Editor.vue'
export default {
  components: {
    Editor
  },
  data() {
    return {
      activeName: 'base',
      tagList: [],
      fileList: [],
      formData: {
        title: '', // 文章标题
        author: '', // 作者
        cateid: '', // 分类id
        click: 0, // 阅读次数
        create_date: '', // 创建时间
        ishot: 0, // 是否推荐
        istop: 0, // 是否置顶
        lovenum: '', // 收藏数量
        pic: '', // 文章封面图片
        tags: [], // 标签
        keywords: '', // SEO关键字
        description: '', // SEO描述
        content: '', // 文章内容
        status: 1 // 文章发布状态
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入文章作者', trigger: 'blur' }
        ],
        cateid: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        click: [
          { required: true, message: '请输入阅读次数', trigger: 'blur' }
        ],
        create_date: [
          { type: 'date', required: true, message: '请选择创建时间', trigger: 'change' }
        ],
        lovenum: [
          { required: true, message: '请输入收藏数量', trigger: 'blur' }
        ],
        pic: [
          { required: true, message: '请上传文章封面', trigger: 'change' }
        ],
        tags: [
          { type: 'array', required: true, message: '请至少选择一个标签', trigger: 'change' }
        ],
        keywords: [
          { required: true, message: '请填写SEO关键字', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请填写SEO描述', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写文章内容', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value === '<p><br/></p>') {
              callback(new Error('请填写文章内容'))
            } else {
              callback()
            }
          }, trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  async created() {
    if (this.$route.params.id) {
      // 编辑状态下获取单个文章详情回显
      const res = await getArticleDetail(this.$route.params.id)
      res.create_date = new Date(res.create_date)
      res.tags = res.tags.split(',')
      if (res.pic) {
        this.fileList.push({ url: 'http://124.223.14.236:8060/' + res.pic })
      }
      this.formData = res
    }
    // 获取所有分类列表渲染下拉框
    if (!this.$store.getters.allCate.id) {
      await this.$store.dispatch('cate/getAllCate')
    }
    // 获取所有标签列表渲染多选框
    const res = await getAllTag()
    this.tagList = res
  },
  methods: {
    // 自定义图片上传
    // async handleUpload(fileData) {
    //   const res = await uploadImg(fileData)
    //   this.formData.pic = res.savePath
    // },
    // 图片上传成功
    handleSuccess(reponse) {
      this.formData.pic = reponse.data.savePath
    },
    // 图片上传之前
    beforeUpload(file) {
      if (file.size > 2 * 1024 * 1024) {
        this.$message.warning('图片大小超过上传限制！')
        return false
      }
    },
    // 提交表单 编辑或新增
    async submit(status) {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          // 处理时间 发布状态 标签
          this.formData.status = status
          this.formData.create_date = +new Date(this.formData.create_date)
          this.formData.tags = this.formData.tags.join(',')
          // 根据是否有查询参数id判断是编辑还是新增
          if (this.$route.params.id) {
            await editArticle(this.formData)
            this.$message.success('编辑文章成功！')
          } else {
            await addArticle(this.formData)
            this.$message.success('发布文章成功!')
          }
          this.$router.push('/content_article')
        } else {
          return this.$message.warning('请将所有信息填写完毕后提交！')
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style></style>
